import { belongsTo, column } from '@adonisjs/lucid/orm'
import CommonBaseModel from '#common/base_model'
import type { BelongsTo } from '@adonisjs/lucid/types/relations'
import StockOrder from '#models/stock_order'
import { ModelAttributes } from '@adonisjs/lucid/types/model'
import type { StockDetail } from '#validators/stock'

export default class StockOutDetail extends CommonBaseModel {
  /** 订单ID */
  @column()
  declare fkStockOrderId: number

  /** 仓库ID */
  @column()
  declare fkWarehouseId: number

  /** 商品ID */
  @column()
  declare fkGoodsId: number

  /** 供应商ID */
  @column()
  declare fkSupplierId: number | null

  /** 进货单位ID */
  @column()
  declare fkBuyUnitId: number

  /** 标准单位ID */
  @column()
  declare fkStandardUnitId: number

  /** 进货单位数量 */
  @column()
  declare buyUnitNumber: number

  /** 购买数量 */
  @column()
  declare buyUnitQuantity: number

  /** 标准单位数量 */
  @column()
  declare standardUnitQuantity: number

  /** 转换标准数量 */
  @column()
  declare quantity: number

  /** 单位单价 */
  @column()
  declare unitPrice: number

  /** 总金额 */
  @column()
  declare totalAmount: number

  /** 状态 */
  @column()
  declare status: number

  /** 备注 */
  @column()
  declare memo: string

  /** 订单信息 */
  @belongsTo(() => StockOrder)
  declare source: BelongsTo<typeof StockOrder>

  static generateCreate(stockInfo: ModelAttributes<StockOrder>, data: StockDetail[]) {
    const newDate = data.map((item) => ({
      ...item,
      fkStockOrderId: stockInfo.id,
      fkWarehouseId: stockInfo.fkWarehouseId,
      quantity: item.buyUnitQuantity * item.buyUnitNumber + item.standardUnitQuantity,
    }))

    return this.createMany(newDate)
  }
}
